package manager
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.system.Security;
	
	import net.ByteSocket;
	import net.DLInProtocolNumber;
	import net.PackageEvent;
	import net.PackageIn;
	import net.SocketEvent;
	import net.SocketOut;
	
	public class SocketManager extends EventDispatcher
	{
		private var _socket:ByteSocket;
		public function SocketManager()
		{
			_socket = new ByteSocket(false);
			_socket.addEventListener(Event.CONNECT,__socketConnected);
			_socket.addEventListener(Event.CLOSE,__socketClose);
			_socket.addEventListener(SocketEvent.DATA,__socketData);
			_socket.addEventListener(ErrorEvent.ERROR,__socketError);
			
			_out = new SocketOut(_socket);
		}
		
		public function connect(ip:String,port:Number):void
		{
			Security.loadPolicyFile("xmlsocket://localhost:843");
			_socket.connect(ip,port);
		}
		
		private function __socketConnected(event:Event) : void 
		{
			trace("socket connected");
		}
		
		private function __socketClose(event : Event) : void 
		{
			DLSvrTest.log("socket closed");
		}
		
		private function __socketError(event:ErrorEvent):void
		{
			trace("socket err");
		}
		
		private function __socketData(event:SocketEvent):void
		{
			try
			{
				var pkg:PackageIn = event.data;
				DLSvrTest.log("......pkg.code......"+pkg.code);
				switch(pkg.code)
				{
					case DLInProtocolNumber.LOGIN:
						dispatchEvent(new PackageEvent(PackageEvent.LOGIN,pkg));
						break;
					case DLInProtocolNumber.SYSTEM_MESSAE:
						dispatchEvent(new PackageEvent(PackageEvent.SYSTEM_MESSAGE,pkg));
						break;
					case DLInProtocolNumber.CHAT:
						dispatchEvent(new PackageEvent(PackageEvent.CHAT,pkg));
						break;
				}
			}catch(e:Error)
			{
				
			}
		}
		
		private static var _instance:SocketManager
		private var _out:SocketOut;
		public static function get Instance():SocketManager
		{
			if(_instance == null)
			{
				_instance = new SocketManager();
			}
			return _instance;
		}
		
		public function get out():SocketOut
		{
			return _out;
		}
	}
}